//
//  PersonRZViewController.m
//  marrymarry
//
//  Created by caofeng on 16/9/25.
//  Copyright © 2016年 cf. All rights reserved.
//
static NSString * wirteCellID =@"WriteNameTableViewCell";
static NSString * PicCellID = @"shenFenPicTableViewCell";
#import "PersonRZViewController.h"
#import "WriteNameTableViewCell.h"
#import "shenFenPicTableViewCell.h"
#import "saveFootView.h"
@interface PersonRZViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
{
    NSString * _NBStr;
 
    BOOL _isOnChecking;
    BOOL _isPassed;
    BOOL _isfailed;
    UIImage * _idCardImg;
    UIImage * _peopleImg;
    
    NSString * _idCard_imgUrl;
    NSString * _people_imgUrl;
    NSString * _realNameStr;
    NSString * _idCardNum;

    NSMutableArray * _myPicArry;
    NSDictionary * _idCarDic;
    NSDictionary * _peopleDic;
    
}
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (strong, nonatomic) saveFootView * footView;
@property (nonatomic,strong) NSMutableArray * dataArry;

@property (nonatomic, strong) NSArray<ZLSelectPhotoModel *> *lastSelectMoldels;
@property (nonatomic, strong) NSArray *arrDataSources;
@property (nonatomic,strong) NSArray * MyPicStrArry;
@property (strong , nonatomic) NSArray * selectPicArry;
@end

@implementation PersonRZViewController

///选择存储img的数组
-(NSArray *)selectPicArry
{
    if (!_selectPicArry) {
        _selectPicArry = [NSArray new];
    }
    return _selectPicArry;
}

-(NSMutableArray *)dataArry
{
    if (!_dataArry) {
        _dataArry = [[NSMutableArray alloc]initWithArray:@[@"1",@"2",@"3"]];
        
    }
    return _dataArry;
}
- (void)viewDidLoad {
    [super viewDidLoad];
     _myPicArry =[NSMutableArray new];
    // Do any additional setup after loading the view.
    self.myTableView.hidden =NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupTableViewFootView];
    
 
}


-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.otherid_str != nil) {
        self.isother = YES;
        [self requestTheNetWith:nil andURL:WATCHCARD_URL andDic:@{@"id":self.otherid_str}];
    }else{
        [self requestTheNetWith:nil andURL:WATCHCARD_URL andDic:@{@"id":[Tools getValueFromNSUserDefaultsByKey:USERID]}];
    }
}
-(void)setupTableViewFootView
{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.myTableView.frame.size.width, 50)];
    self.myTableView.tableFooterView = footView;
    self.footView = [[[NSBundle mainBundle] loadNibNamed:@"saveFootView" owner:self options:nil] lastObject];
    self.footView.frame = CGRectMake(0, 0,self.myTableView.frame.size.width,50);
    [footView addSubview: self.footView];
    self.footView.saveFootBtn.layer.cornerRadius = 5;
    [self.footView.saveFootBtn addTarget:self action:@selector(pushMyPhoto) forControlEvents:UIControlEventTouchUpInside];
}
-(void)pushMyPhoto
{
    if (_realNameStr == nil) {
        [SVProgressHUD showErrorWithStatus:@"请填写您的真实姓名"];
        return;
    }else if (_idCardNum == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"请填写您的身份证号"];
        return;
    }else if (_idCardImg == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"请选上传您的身份证照"];
        return;
    }else if (_peopleImg == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"请上传您的手持身份证照"];
        return;
    }
    [self requestTheNetWith:self.selectPicArry andURL:UPDATEMYSELF_URL andDic:@{@"id":[Tools getValueFromNSUserDefaultsByKey:USERID],@"realName":_realNameStr,@"cdcard":_idCardNum}];
}


#pragma mark UITableViewDatasource,UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.dataArry.count>0) {
        return self.dataArry.count;
    }else
    {
        return  0;
    }
    
    
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || indexPath.section == 1) {
        WriteNameTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:wirteCellID];
        if (!cell) {
            cell = [[WriteNameTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:wirteCellID];
        }
        if (indexPath.section ==1) {
            cell.writeTextField.placeholder = @"填写身份证号码";
        }
        
        if (indexPath.section == 0) {
            cell.writeTextField.tag = 2001;
        }else{
            cell.writeTextField.tag = 2002;
        }
        [cell.writeTextField addTarget:self action:@selector(textFieldChangeValue:) forControlEvents:UIControlEventEditingChanged];
        if (indexPath.section == 0) {
            if (_realNameStr !=nil) {
                cell.writeTextField.text = _realNameStr;
            }else{
                cell.writeTextField.text = @"";
            }
        }
        if (indexPath.section == 1) {
            if (_idCardNum != nil) {
                cell.writeTextField.text = _idCardNum;
            }else {
                cell.writeTextField.text = @"";
            }
        }
        
        if (_isOnChecking||self.isother||_isPassed) {
            cell.writeTextField.userInteractionEnabled = NO;
        }else{
            cell.writeTextField.userInteractionEnabled= YES;
        }

        return cell;
    }else
    {
        shenFenPicTableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:PicCellID];
        if (!cell) {
            cell = [[shenFenPicTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:PicCellID];
            
        }
        
        if (_idCardImg != nil || _idCard_imgUrl !=nil) {
            if (_isOnChecking||self.isother ||_isPassed) {
                cell.rightDeleBtn.hidden= YES;
                cell.rightCImgView.userInteractionEnabled = NO;
            }else{
                cell.rightDeleBtn.hidden = NO;
            }
            cell.rightDeleBtn.tag = 1;
            [cell.rightDeleBtn addTarget:self action:@selector(deletImgBtn:) forControlEvents:UIControlEventTouchUpInside];
            if (_idCard_imgUrl != nil) {
                [cell.rightCImgView setImageWithURL:[NSURL URLWithString:_idCard_imgUrl]];
            }else{
                [cell.rightCImgView setImage:_idCardImg];
            }
        }else{
            if (self.isother) {
                cell.rightCImgView.hidden = YES;
            }
            cell.rightDeleBtn.hidden = YES;
            cell.rightCImgView.userInteractionEnabled = YES;
            [cell.rightCImgView setImage:[UIImage imageNamed:@"tianjia.jpg"]];
            CFUITapGestureRecognizer * myTap = [[CFUITapGestureRecognizer alloc]initWithTarget:self action:@selector(addphotoWithTap:)];
            myTap.usertype = @"1";
            [cell.rightCImgView addGestureRecognizer:myTap];
        }
        
        
        
        if (_peopleImg != nil || _people_imgUrl !=nil) {
            if (_isOnChecking||self.isother ||_isPassed) {
                cell.leftDeleBtn.hidden= YES;
                cell.leftPCImgView.userInteractionEnabled = NO;
            }else{
                cell.leftDeleBtn.hidden = NO;
            }
            cell.leftDeleBtn.tag = 2;
            [cell.leftDeleBtn addTarget:self action:@selector(deletImgBtn:) forControlEvents:UIControlEventTouchUpInside];
            if (_people_imgUrl != nil) {
                [cell.leftPCImgView setImageWithURL:[NSURL URLWithString:_people_imgUrl]];
            }else{
                [cell.leftPCImgView setImage:_peopleImg];
            }
        }else{
            if (self.isother) {
                cell.leftPCImgView.hidden = YES;
            }
            cell.leftDeleBtn.hidden = YES;
            cell.leftPCImgView.userInteractionEnabled = YES;
            [cell.leftPCImgView setImage:[UIImage imageNamed:@"tianjia.jpg"]];
            CFUITapGestureRecognizer * myTap = [[CFUITapGestureRecognizer alloc]initWithTarget:self action:@selector(addphotoWithTap:)];
            myTap.usertype = @"2";
            [cell.leftPCImgView addGestureRecognizer:myTap];
        }

        
        
        return cell;
   
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }else
    {
        return 10;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        return 300;
    }else{
    return 60;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}




-(void)textFieldChangeValue:(UITextField*)textField
{
    /** 姓名 **/
    if (textField.tag == 2001) {
        _realNameStr = textField.text;
    }else if (textField.tag == 2002)
    {
        _idCardNum = textField.text;
    }
}

-(void)deletImgBtn:(UIButton * )deleBtn
{
    if (deleBtn.tag == 1) {
        _idCardImg = nil;
    }else{
        _peopleImg = nil;
    }

    
    [self.myTableView reloadData];
}

///添加照片
-(void)addphotoWithTap:(CFUITapGestureRecognizer * )myTap
{
    
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    //设置照片最大选择数
    actionSheet.maxSelectCount = 1;
    //设置照片最大预览数
    actionSheet.maxPreviewCount = 20;
    actionSheet.isInVC = YES;
    weakify(self);
    [actionSheet showWithSender:self animate:YES lastSelectPhotoModels:self.lastSelectMoldels completion:^(NSArray<UIImage *> * _Nonnull selectPhotos, NSArray<ZLSelectPhotoModel *> * _Nonnull selectPhotoModels) {
        strongify(weakSelf);
        strongSelf.arrDataSources = selectPhotos;
        strongSelf.lastSelectMoldels = selectPhotoModels;
        NSLog(@"%@", selectPhotos);
        self.selectPicArry = strongSelf.arrDataSources;
        if ([myTap.userInfo isEqualToString:@"1"]) {
            _idCardImg = self.selectPicArry[0];
        }else{
            _peopleImg = self.selectPicArry[0];
        }
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:2];
        [self.myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    }];
    
}



#pragma mark --------------网络请求
-(void)requestTheNetWith:(NSArray *)myRequestArry andURL:(NSString *)myurl andDic:(NSDictionary *)myDic;
{ [_myPicArry removeAllObjects];
    if (myRequestArry.count> 0) {
        
        _idCarDic = @{@"imgname":@"cdcardimg",@"pic":myRequestArry[0]};
        _peopleDic = @{@"imgname":@"cdcardimg",@"pic":myRequestArry[1]};
        [_myPicArry addObject:_idCarDic];
        [_myPicArry addObject:_peopleDic];
        [[LJFNetworkingManager shareManager] POST:myurl upLoadImages:_myPicArry parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
            if (code == 1) {
                [SVProgressHUD showSuccessWithStatus:@"上传成功"];
                [self.footView.saveFootBtn setTitle:@"正在审核" forState:UIControlStateNormal];
                self.footView.saveFootBtn.userInteractionEnabled = NO;
                self.footView.saveFootBtn.backgroundColor = [UIColor lightGrayColor];
                _isOnChecking = YES;
                [self.myTableView reloadData];
            }
            
        } failure:^(NSError *error) {
            NSLog(@"失败");
            
        } showHUD:nil];
        [self.myTableView reloadData];
        
    }else
    {
        [[LJFNetworkingManager shareManager] POST:myurl parameters:myDic success:^(id returnData, int code, NSString *msg) {
            NSLog(@"%@",msg);
            
            if (code == 1) {
                NSLog(@"%@",returnData);
                //                _houseImg_Url = returnData[@"deedPhoto"];
                if ([returnData[@"status"] intValue] == 0) {
                    _isOnChecking = YES;

                    
                  
                    [self setFootViewBtn];
                }else if ([returnData[@"status"] intValue] == 1)
                {
                    _isPassed = YES;
                    [self setFootViewBtn];
                }
                else if ([returnData[@"status"] intValue] == 2)
                {
                    _isfailed = YES;
                    [self setFootViewBtn];
                }
                else{
                    _isOnChecking = NO;
                    
                }
                NSArray * myidCarArr = [returnData[@"idcardPhoto"] componentsSeparatedByString:@","];
                _people_imgUrl = myidCarArr[0];
                _idCard_imgUrl = myidCarArr[1];
                _realNameStr = @"";
                _idCardNum = @"";
                [self.myTableView reloadData];
            }
            else{
                if (self.isother) {
                    self.footView.hidden = YES;
                    [self.myTableView reloadData];
                }
            }
            
        } failure:^(NSError *error) {
            NSLog(@"%@",error);
        } showHUD:self.view];
    }
    
    
    
}


-(void)setFootViewBtn
{
    if (_isOnChecking) {
        [self.footView.saveFootBtn setTitle:@"正在审核" forState:UIControlStateNormal];
        self.footView.saveFootBtn.userInteractionEnabled = NO;
        self.footView.saveFootBtn.backgroundColor = [UIColor lightGrayColor];
    }else if(_isPassed)
    {
        [self.footView.saveFootBtn setTitle:@"审核通过" forState:UIControlStateNormal];
        self.footView.saveFootBtn.userInteractionEnabled = NO;
        self.footView.saveFootBtn.backgroundColor =RGB(0, 234, 202);
    }else if (_isfailed)
    {
        [self.footView.saveFootBtn setTitle:@"审核不通过" forState:UIControlStateNormal];
        self.footView.saveFootBtn.userInteractionEnabled = YES;
        self.footView.saveFootBtn.backgroundColor =RGB(0, 234, 202);
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
